//
//  MapNaviController.m
//  HarmonizePub
//
//  Created by rzhy on 2016/10/27.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "MapNaviController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "Config.h"
#import <UINavigationController+FDFullscreenPopGesture.h>

@interface MapNaviController () <BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,BMKRouteSearchDelegate>

@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *dockView;
@property (strong, nonatomic) BMKRouteSearch *search; // 搜索服务
@property (strong, nonatomic) BMKLocationService *locationService; // 定位服务
@property (strong, nonatomic) NSString *type; // 1.步行 2.驾车 3.公交
@property (assign, nonatomic) NSInteger count;
@property (strong, nonatomic) CLLocationManager *locationManager;

@end

@implementation MapNaviController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"地图导航";
    self.fd_interactivePopDisabled = YES;
    
    self.type = @"1";
    self.count = 0;
    [self setMapViewAttr];
    [self createButtonWith];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    _mapView.delegate = nil;
    _search.delegate = nil;
    [self.locationService stopUserLocationService];
    self.count = 0;
}

#pragma mark - set MapView
- (void)setMapViewAttr {
    self.mapView.delegate = self;
    // 地图比例尺级别，在手机上当前可使用的级别为3-21级
    self.mapView.zoomLevel = 14;
    // 设定是否显示定位图层
    self.mapView.showsUserLocation = YES;
    // 由于iOS8中定位的授权机制改变 需要进行手动授权
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8) {
        _locationManager = [[CLLocationManager alloc] init];
        // 获取授权认证
        [_locationManager requestAlwaysAuthorization];
        [_locationManager requestWhenInUseAuthorization];
        [_locationManager startUpdatingLocation];
    }
    // 定位服务
    self.locationService = [[BMKLocationService alloc] init];
    self.locationService.delegate = self;
    // 用户开始定位
    [self.locationService startUserLocationService];
    // 动态更新我的位置数据
    [self.mapView updateLocationData:self.locationService.userLocation];
    // 当前地图的中心点，改变该值时，地图的比例尺级别不会发生变化
    self.mapView.centerCoordinate = self.locationService.userLocation.location.coordinate;
}

#pragma mark - create Button
- (void)createButtonWith {
    NSArray *imageNameArray = @[@"walking.png", @"drive.png", @"bus.png"];
    CGFloat buttonH = 30.0f;
    CGFloat buttonY = 5.0f;
    NSInteger count = imageNameArray.count;
    for (NSInteger i = 0; i < count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i + 1;
        UIImage *image = [UIImage imageNamed:imageNameArray[i]];
        [button setImage:image forState:UIControlStateNormal];
        CGFloat buttonW = image.size.width / (image.size.height / buttonH);
        CGFloat buttonX = XHScreenWidth / count * i + ((XHScreenWidth / count - buttonW) / 2);
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        [button addTarget:self action:@selector(buttonClickEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.dockView addSubview:button];
    }
}

#pragma mark - button Event
- (void)buttonClickEvent:(UIButton *)sender {
    self.count = 0;
    self.type = [NSString stringWithFormat:@"%d", sender.tag];
}

#pragma mark - BMKLocationService delegate
#pragma mark 用户位置更新后，会调用此函数
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    // 动态更新我的位置数据
    [self.mapView updateLocationData:userLocation];
    if (self.count == 0) {
        self.count++;
        // 当前地图的中心点，改变该值时，地图的比例尺级别不会发生变化
        self.mapView.centerCoordinate = userLocation.location.coordinate;
        // 搜索服务
        _search = [[BMKRouteSearch alloc] init];
        _search.delegate = self;
        // 线路检索节点信息, 一个路线检索节点可以通过经纬度坐标或城市名加地名确定
        BMKPlanNode *start = [[BMKPlanNode alloc] init];
        // 节点名称
        start.name = @"我的位置";
        // 节点坐标
        start.pt = userLocation.location.coordinate;
        BMKPlanNode *end = [[BMKPlanNode alloc] init];
        // 节点名称
        end.name = @"连江";
        // 节点所在城市
        end.cityName = @"福州";
        // 判断交通方式
        if ([self.type isEqualToString:@"1"]) {
            // 步行查询基础信息类
            BMKWalkingRoutePlanOption *walkingSearchOption = [[BMKWalkingRoutePlanOption alloc] init];
            // 检索的起点，可通过关键字、坐标两种方式指定。cityName和cityID同时指定时，优先使用cityID
            walkingSearchOption.from = start;
            // 检索的终点，可通过关键字、坐标两种方式指定。cityName和cityID同时指定时，优先使用cityID
            walkingSearchOption.to = end;
            // 步行路线检索, 返回结果在 BMKRouteSearchDelegate 的 onGetWalkingRouteResult 通知
            BOOL flag = [_search walkingSearch:walkingSearchOption];
            if (!flag) XHLog(@"步行检索失败");
        } else if ([self.type isEqualToString:@"2"]) {
            // 驾车查询基础信息类
            BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc] init];
            drivingRouteSearchOption.from = start;
            drivingRouteSearchOption.to = end;
            // 驾乘路线检索, 返回结果在 BMKRouteSearchDelegate 的 onGetDrivingRouteResult 通知
            BOOL flag = [_search drivingSearch:drivingRouteSearchOption];
            if (flag) XHLog(@"car检索发送失败");
        } else if ([self.type isEqualToString:@"3"]) {
            // 公交查询基础信息类
            BMKTransitRoutePlanOption *transitRouteSearchOption = [[BMKTransitRoutePlanOption alloc] init];
            transitRouteSearchOption.from = start;
            transitRouteSearchOption.to = end;
            // 城市名，用于在哪个城市内进行检索
            transitRouteSearchOption.city = @"福州市";
            // 公交路线检索（仅支持市内）, 返回结果在 BMKRouteSearchDelegate 的 onGetTransitRouteResult 通知
            BOOL flag = [_search transitSearch:transitRouteSearchOption];
            if (flag) XHLog(@"bus检索发送失败");
        }
    }
//    XHLog(@"用户位置更新 lat %f,long %f",userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
}

#pragma mark - BMKRouteSearch delegate
#pragma mark 步行搜索结果
- (void)onGetWalkingRouteResult:(BMKRouteSearch *)searcher result:(BMKWalkingRouteResult *)result errorCode:(BMKSearchErrorCode)error {
    // 当前地图View的已经添加的标注数组
    NSArray *array = [NSArray arrayWithArray:_mapView.annotations];
    // 移除一组标注
    [_mapView removeAnnotations:array];
    // 当前mapView中已经添加的Overlay数组
    array = [NSArray arrayWithArray:_mapView.overlays];
    // 移除一组Overlay
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        // 获取成功
        // 一条步行路线
        BMKWalkingRouteLine *plan = (BMKWalkingRouteLine *)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            // 驾车路线中的一个路段
            BMKWalkingStep *transitStep = [plan.steps objectAtIndex:i];
            if (i == size - 1) {
                // 一个点的annotation
                BMKPointAnnotation *item = [[BMKPointAnnotation alloc] init];
                // 该点的坐标
                item.coordinate = plan.terminal.location;
                // 要显示的标题
                item.title = @"连江";
                // 添加起点标注
                [_mapView addAnnotation:item];
            }
            // 轨迹点总数累计
            // 路段所经过的地理坐标集合内点的个数
            planPointCounts += transitStep.pointsCount;
        }
        // 轨迹点
        BMKMapPoint *temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            // 步行路线中的一个路段
            BMKWalkingStep *transitStep = [plan.steps objectAtIndex:j];
            for(int k = 0; k<transitStep.pointsCount; k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
        }
        // 通过points构建BMKPolyline
        // 根据指定坐标点生成一段折线
        BMKPolyline *polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        // 添加路线overlay
        [_mapView addOverlay:polyLine];
        delete []temppoints;
    } else
        [self setAlertViewWithMessage:@"暂无推荐的步行路线!"];
}

#pragma mark 驾车搜索结果
- (void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error {
    NSArray *array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error ==  BMK_SEARCH_NO_ERROR) {
        // 获取成功
        // 驾车路线
        BMKDrivingRouteLine *plan = (BMKDrivingRouteLine *)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            // 步行路线中的一个路段
            BMKDrivingStep *transitStep = [plan.steps objectAtIndex:i];
            if (i == size - 1) {
                BMKPointAnnotation *item = [[BMKPointAnnotation alloc] init];
                item.coordinate = plan.terminal.location;
                item.title = @"连江";
                [_mapView addAnnotation:item];
            }
            // 轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 轨迹点
        BMKMapPoint *temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            // 驾车路线中的一个路段
            BMKDrivingStep *transitStep = [plan.steps objectAtIndex:j];
            int k = 0;
            for (k = 0; k<transitStep.pointsCount; k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
        }
        // 通过points构建BMKPolyline
        BMKPolyline *polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        // 添加路线overlay
        [_mapView addOverlay:polyLine];
        delete []temppoints;
        
        
    } else
        [self setAlertViewWithMessage:@"获取失败，请重试！"];
}

#pragma mark 公交搜索结果
- (void)onGetTransitRouteResult:(BMKRouteSearch *)searcher result:(BMKTransitRouteResult *)result errorCode:(BMKSearchErrorCode)error {
    NSArray *array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        // 获取成功
        // 一条驾车路线
        BMKDrivingRouteLine *plan = (BMKDrivingRouteLine *)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            // 公交路线中的一个路段
            BMKMassTransitSubStep *transitStep = [plan.steps objectAtIndex:i];
            if (i == size - 1) {
                BMKPointAnnotation *item = [[BMKPointAnnotation alloc] init];
                item.coordinate = plan.terminal.location;
                item.title = @"连江";
                [_mapView addAnnotation:item];
            }
            // 轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 轨迹点
        BMKMapPoint *temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            // 公交路线中的一个路段
            BMKMassTransitSubStep *transitStep = [plan.steps objectAtIndex:j];
            int k = 0;
            for (k = 0; k < transitStep.pointsCount; k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
        }
        // 通过points构建BMKPolyline
        BMKPolyline *polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        // 添加路线overlay
        [_mapView addOverlay:polyLine];
        delete []temppoints;
        
        
    } else
        [self setAlertViewWithMessage:@"并无公交线路!"];
}

#pragma mark - BMKMapView delegate 
#pragma mark 根据overlay生成对应的View
- (BMKOverlayView *)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay {
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        // 折线
        BMKPolylineView *polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        // 填充颜色
        polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
        // 画笔颜色
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        // 画笔宽度，默认为0
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}

#pragma mark - alertView
- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"查询失败" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
